package com.huilian.iotbox.admin.quartz.job;

import com.huilian.iotbox.admin.service.DeviceService;
import com.huilian.iotbox.data.cmd.PositiveDataFrameCMD;
import com.huilian.iotbox.aliyun.service.PubService;
import com.huilian.iotbox.data.dto.DeviceDto;
import com.huilian.iotbox.data.enums.DeviceTypeEnum;
import com.huilian.iotbox.data.po.Device;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 定时任务查询外部设备的参数
 *
 * @author chenqiwen
 * @CreateDate: 2021-09-15-12-49
 * @Description:
 */
@Slf4j
public class QueryBaseParamByExternalDeviceJob implements BaseJob {

    @Value("${huilian.iot.productKey}")
    private String productKey;
    @Autowired
    PubService pubService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ErrorLogCommonService errorLogCommonService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        DeviceDto deviceCondition = new DeviceDto();
        deviceCondition.setNetworkIntensity(1);
        List<Device> deviceList = deviceService.findAllDeviceByCondition(deviceCondition);

        for (Device device : deviceList) {
            try {
                if (device.getPulseSwitchState()) {
                    log.info(device.getDeviceNo() + "开启了脉冲");
                    continue;
                }

                String tcp  = PositiveDataFrameCMD.queryBaseParams();

                log.info("定时任务查询外部设备的参数tcp:" + tcp);
                String penetrate = PositiveDataFrameCMD.penetrate(tcp);
                log.info(device.getDeviceNo() + "定时任务查询外部设备的参数penetrate:" + penetrate);
                pubService.pub(penetrate, device.getDeviceNo(), productKey);
            } catch (Exception e) {
                e.printStackTrace();
                errorLogCommonService.writerInfoException(device.getDeviceNo() + "查询外部设备参数出错", device, e);
            }
        }
    }
}
